<template>
  <!-- 头部 -->
  <div class="title">
    <h1>商品管理</h1>
    <el-button type="primary" @click="handleAdd()">增加商品</el-button>
  </div>
  <!-- 商品列表 -->
  <el-table :data="filterTableData" style="width: 100%">
    <el-table-column label="商品id" prop="id" />
    <el-table-column label="商品名称" prop="name" />
    <el-table-column label="商品数量" prop="store" />
    <el-table-column label="商品价格" prop="price" />
    <el-table-column label="商品图片" prop="image">
      <template v-slot="scope">
        <img :src="scope.row.image" alt="" width="90" height="90" />
      </template> </el-table-column
    >>
    <el-table-column align="right">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
          >Edit</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          >Delete</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <!-- 删除弹窗 -->
  <el-dialog
    v-model="centerDialogVisible"
    title="Warning"
    width="30%"
    align-center
  >
    <span>你确定要删除{{ ProductsInfo }}的内容么？</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="del()"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="修改商品详情">
    <el-form :model="form">
      <el-form-item label="商品名字" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品描述" :label-width="formLabelWidth">
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品价格" :label-width="formLabelWidth">
        <el-input v-model="form.price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品数量" :label-width="formLabelWidth">
        <el-input v-model="form.store" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品点赞" :label-width="formLabelWidth">
        <el-input v-model="form.star" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品图片" :label-width="formLabelWidth">
        <el-upload
          v-model:file-list="form.fileList"
          action="#"
          :http-request="uploadAction"
          list-type="picture-card"
          :headers="headerObj"
          :on-preview="handlePictureCardPreview1"
          :on-remove="handleRemove1"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl1" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="EditProducts()"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 增加弹窗 -->
  <el-dialog v-model="dialogAddFormVisible" title="增加商品">
    <el-form :model="Form">
      <el-form-item label="商品名字" :label-width="formLabelWidth">
        <el-input v-model="Form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品描述" :label-width="formLabelWidth">
        <el-input v-model="Form.description" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品价格" :label-width="formLabelWidth">
        <el-input v-model="Form.price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品数量" :label-width="formLabelWidth">
        <el-input v-model="Form.store" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品图片" :label-width="formLabelWidth">
        <!--        <el-image style="width: 100px; height: 100px" :src="form.image"  />-->
        <el-upload
          v-model:file-list="Form.fileList"
          action="http://43.139.124.13:8888/product/upload"
          list-type="picture-card"
          :headers="headerObj"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取消</el-button>
        <el-button type="primary" @click="AddProducts()"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUpdated, reactive, ref } from "vue";
import {
  addProductsApi,
  delProductsApi,
  getProductsApi,
  getProductsEditsApi,
  updata,
} from "../api/products.js";
import { ElMessage, UploadFile, UploadRawFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";

// 定义ts接口
interface User {
  id: 0;
  date: string;
  name: string;
  address: string;
}
// 定义ref
const productsList = ref();
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const form = ref({
  fileList: [] as any,
  name: "",
  store: "",
  star: "",
  price: "",
  description: "",
  image: "",
});
const Form = ref({
  fileList: [],
  name: "",
  store: "",
  price: 0,
  description: "",
  image: "",
});
const delId = ref();
const postId = ref();
const dialogAddFormVisible = ref(false);
const dialogImageUrl = ref("");
const dialogImageUrl1 = ref("");
const dialogVisible = ref(false);
//获取token
// @ts-ignore
const Token = JSON.parse(localStorage.getItem("login")).user.token;
const headerObj = {
  token: Token,
};

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const handleRemove1: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview1: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl1.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 删除弹框
const centerDialogVisible = ref<boolean>(false);
const ProductsInfo = ref();
const search = ref("");
const filterTableData = computed(() =>
  productsList.value?.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
);

// 商品列表
const getProducts = async () => {
  const res = await getProductsApi();
  productsList.value = res.data.data;
};
onMounted(() => {
  getProducts();
});
onUpdated(() => {
  if (!dialogFormVisible.value) {
    form.value.fileList.length = 0;
  }
});
// 删除
const del = async () => {
  const res = await delProductsApi(delId.value);

  if (res.data.code == "200") {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: "删除失败",
      type: "error",
    });
  }
  setTimeout(() => {
    centerDialogVisible.value = false;
    getProducts();
  }, 1000);
};
const handleDelete = (index: number, row: User) => {
  ProductsInfo.value = row?.name;
  centerDialogVisible.value = true;
  delId.value = row?.id;
};

// 文件上传
const uploadFile = ref();
const state = reactive({
  bannerUrl: "",
  fileList: [],
  fileName: "",
});

const uploadAction = async (option: any) => {
  let param = new FormData();
  param.append("file", option.file);
  updata(param).then((res) => {
    if (res.data.code == "200") {
      uploadFile.value = res.data.msg;
    }
  });
};
// 修改商品
const handleEdit = (index: number, row: any) => {
  dialogFormVisible.value = true;

  form.value.name = row.name;
  form.value.price = row.price;
  form.value.star = row.star;
  form.value.store = row.store;
  form.value.description = row.description;
  form.value.fileList.push({ url: row.image });
  postId.value = row?.id;
  console.log(row.image);
};
const EditProducts = async () => {
  const productValue = {
    ...form.value,
    id: postId.value,
    store: parseInt(form.value.store),
    image: uploadFile.value,
  };
  console.log(form.value);
  const res = await getProductsEditsApi(productValue);
  if (res.data.code == "200") {
    ElMessage({
      message: "修改成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: "修改失败",
      type: "error",
    });
  }
  setTimeout(() => {
    dialogFormVisible.value = false;
    getProducts();
  }, 1000);
};
//增加商品
const handleAdd = () => {
  dialogAddFormVisible.value = true;
};
const AddProducts = async () => {
  console.log(Form.value);
  const addProduct = {
    ...Form.value,
    image: Form.value?.fileList[0].response.msg,
  };
  const res = await addProductsApi(addProduct);
  if (res.data.code == "200") {
    ElMessage({
      message: "新增成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: "新增失败",
      type: "error",
    });
  }
  setTimeout(() => {
    dialogAddFormVisible.value = false;
    getProducts();
  }, 1000);
  console.log(res);
};
</script>

<style scoped>
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
